package com.lyl.security.common.sercurity.config;

import com.lyl.security.common.sercurity.handler.AccessFailureHandler;
import com.lyl.security.common.sercurity.handler.AuthFailureHandler;
import com.lyl.security.common.sercurity.model.properties.SecurityProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final SecurityProperties securityProperties;
    private final AuthFailureHandler authFailureHandler;
    private final AccessFailureHandler accessFailureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .cors().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeHttpRequests()
                .antMatchers(securityProperties.getExcludeUrls()).permitAll()
                .anyRequest().authenticated();

        //异常处理程序
        http.exceptionHandling()
                .authenticationEntryPoint(authFailureHandler)
                .accessDeniedHandler(accessFailureHandler);
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
